import { createRoute } from "../createRouterMap";

function runQueue(queue, iterator, cb) {
    //异步执行
    function step(index) {
        if (index >= queue.length) return cb()
        let hook = queue[index++]
        iterator(hook, () => step(index++))
    }
    step(0)
}
class History {
    constructor(router) {
        this.router = router
        this.current = createRoute(null, { path: '/' })//保存当前最新的路由记录
    }
    push(to) {
        this.transitionTo(to, () => {
            window.location.hash = to
        })
    }
    transitionTo(location, cb) {
        const current = this.current
        let router = this.router.match(location)
        // let current = createRoute(router, { path: location })
        // console.log(current);
        //获取全局守卫
        //列队处理
        let queue = [].concat(this.router.beforeHooks)
        const iterator = ((hook, next) => {
            hook(current, router, () => {
                next()
            })
        })
        this.current = router
        runQueue(queue, iterator, () => {
            this.cb && this.cb(this.current)
            cb && cb()
        })
    }
    listen(cb) {
        this.cb = cb
    }
}
export {
    History
}